<template>
  <BasicForm ref="onlineFormRef" @register="registerForm" />
</template>
<script lang="ts">
  import { ref, watch, defineComponent, unref, toRaw } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { defHttp } from '/@/utils/http/axios';
  import { useFormItems, loadFormFieldsDefVal, getRefPromise } from '../../use/useAutoForm';

  const baseUrl = '/api-online/online/cgform/api/subform';

  export default defineComponent({
    name: 'OnlineSubForm',
    components: {
      BasicForm,
    },
    props: {
      properties: {
        type: Object,
        required: true,
      },
      mainId: {
        type: String,
        default: '',
      },
      table: {
        type: String,
        default: '',
      },
      formTemplate: {
        type: Number,
        default: 1,
      },
      requiredFields: {
        type: Array,
        default: [],
      },
      isUpdate: {
        type: Boolean,
        default: false,
      },
      disabled: {
        type: Boolean,
        default: false,
      },
    },
    emits: ['formChange'],
    setup(props, { emit }) {
      console.log('进入online子表表单页面》》》》' + props.table);
      const onlineFormRef = ref(null);
      const formRendered = ref(false);
      useMessage();
      const {
        formSchemas,
        defaultValueFields,
        changeDataIfArray2String,
        tableName,
        dbData,
        checkOnlyFieldValue,
        fieldDisplayStatus,
        createFormSchemas,
        baseColProps,
      } = useFormItems(props, onlineFormRef);
      const [registerForm, { setProps, validate, resetFields, setFieldsValue, getFieldsValue }] = useForm({
        schemas: formSchemas,
        showActionButtonGroup: false,
        baseColProps,
      });
      watch(
        () => props.table,
        () => {
          tableName.value = props.table;
        },
        { immediate: true }
      );
      watch(
        () => props.properties,
        (valueObj) => {
          console.log('主表properties改变', props.properties);
          formRendered.value = false;
          addFormChangeEvent();
          createFormSchemas(props.properties, props.requiredFields, checkOnlyFieldValue);
          formRendered.value = true;
        },
        { deep: true, immediate: true }
      );
      watch(
        () => props.mainId,
        (valueObj) => {
          console.log('主表ID改变', props.mainId);
          setTimeout(() => {
            resetSubForm();
          }, 100);
        },
        { immediate: true }
      );
      watch(
        () => props.disabled,
        (val) => {
          setProps({ disabled: val });
        }
      );
      async function addFormChangeEvent() {
        const formRefObject = await getRefPromise(onlineFormRef);
        formRefObject.$formValueChange = (field2, value) => {
          const emitArgument = { [field2]: value };
          emit('formChange', emitArgument);
        };
      }
      function handleDefaultValue2() {
        if (unref(props.isUpdate) === false) {
          const fieldProperties = toRaw(defaultValueFields[tableName.value]);
          loadFormFieldsDefVal(fieldProperties, (values) => {
            setFieldsValue(values);
          });
        }
      }
      async function resetSubForm() {
        await getRefPromise(formRendered);
        await resetFields();
        handleDefaultValue2();
        const { table, mainId } = props;
        if (!table || !mainId) {
          return;
        }
        const values = await loadData(table, mainId);
        dbData.value = values;
        await setFieldsValue(values);
      }
      function loadData(table, mainId) {
        const url = `${baseUrl}/${table}/${mainId}`;
        return new Promise((resolve, reject) => {
          defHttp.get({ url }, { isTransformResponse: false }).then((res) => {
            console.log(res);
            if (res.success) {
              resolve(res.data);
            } else {
              console.log(res.msg);
              reject();
            }
          });
        }).finally(() => {
          dbData.value = '';
        });
      }
      function getAll() {
        return new Promise((resolve, reject) => {
          validate()
            .then(() => {
              let formData = getFieldsValue();
              formData = changeDataIfArray2String(formData);
              resolve(formData);
            })
            .catch((e) => {
              reject(e);
            });
        });
      }
      function getFormEvent() {
        const row = getFieldsValue();
        if (!row.id) {
          row.id = 'sub-change-temp-id';
        }
        return {
          row,
          target: context,
        };
      }
      function setValues(values) {
        setFieldsValue(values);
      }
      const context = {
        onlineFormRef,
        baseColProps,
        formSchemas,
        registerForm,
        setFieldsValue,
        getFieldsValue,
        getFormEvent,
        setValues,
        getAll,
        sh: fieldDisplayStatus,
      };
      return context;
    },
  });
</script>
<style scoped></style>
